import { Config, Groups, DrawRequest, DrawResponse } from '../types.ts';

// API基础URL，可以通过环境变量配置
const API_BASE = import.meta.env?.VITE_API_BASE || '';

/**
 * 获取配置信息
 */
export async function getConfig(): Promise<Config> {
  const response = await fetch(`${API_BASE}/api/config`);
  if (!response.ok) {
    throw new Error('获取配置失败');
  }
  return response.json();
}

/**
 * 获取当前分组情况
 */
export async function getGroups(): Promise<Groups> {
  const response = await fetch(`${API_BASE}/api/groups`);
  if (!response.ok) {
    throw new Error('获取分组数据失败');
  }
  return response.json();
}

/**
 * 摇号
 */
export async function draw(request: DrawRequest): Promise<DrawResponse> {
  const response = await fetch(`${API_BASE}/api/draw`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(request),
  });
  
  const result = await response.json();
  
  if (!response.ok) {
    // 如果响应不成功，但有错误信息，返回错误信息
    return {
      success: false,
      error: result.error || '摇号失败，请重试',
    };
  }
  
  return result;
}

/**
 * 重置数据（仅用于测试）
 */
export async function reset(): Promise<{ success: boolean; message?: string; error?: string }> {
  const response = await fetch(`${API_BASE}/api/reset`, {
    method: 'POST',
  });

  if (!response.ok) {
    throw new Error('重置失败');
  }

  return response.json();
}

// ==================== 比赛管理API ====================

/**
 * 获取比赛状态
 */
export async function getTournamentStatus(): Promise<import('../types').TournamentStatusResponse> {
  const response = await fetch(`${API_BASE}/api/tournament/status`);
  return response.json();
}

/**
 * 注册队伍（管理员操作）
 */
export async function registerTeams(request: import('../types').StartTournamentRequest): Promise<import('../types').StartTournamentResponse> {
  const response = await fetch(`${API_BASE}/api/tournament/register-teams`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(request),
  });
  return response.json();
}



/**
 * 提交比赛结果
 */
export async function submitMatchResult(request: import('../types').SubmitMatchResultRequest): Promise<import('../types').SubmitMatchResultResponse> {
  const response = await fetch(`${API_BASE}/api/tournament/match-result`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(request),
  });
  return response.json();
}

/**
 * 进入下一轮
 */
export async function advanceRound(request: import('../types').AdvanceRoundRequest): Promise<import('../types').AdvanceRoundResponse> {
  const response = await fetch(`${API_BASE}/api/tournament/advance-round`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(request),
  });
  return response.json();
}

/**
 * 重置比赛
 */
export async function resetTournament(): Promise<{ success: boolean; message?: string; error?: string }> {
  const response = await fetch(`${API_BASE}/api/tournament/reset`, {
    method: 'POST',
  });
  return response.json();
}

// ==================== 轮次管理API ====================

/**
 * 获取比赛配置
 */
export async function getTournamentConfig(): Promise<import('../types').GetConfigResponse> {
  const response = await fetch(`${API_BASE}/api/admin/config`);
  return response.json();
}

/**
 * 更新比赛配置
 */
export async function updateTournamentConfig(config: import('../types').TournamentConfig): Promise<import('../types').GetConfigResponse> {
  const response = await fetch(`${API_BASE}/api/admin/config`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ config }),
  });
  return response.json();
}

/**
 * 添加轮次
 */
export async function addRound(request: import('../types').AddRoundRequest): Promise<import('../types').AddRoundResponse> {
  const response = await fetch(`${API_BASE}/api/admin/rounds`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(request),
  });
  return response.json();
}

/**
 * 更新轮次
 */
export async function updateRound(roundName: string, request: import('../types').UpdateRoundRequest): Promise<import('../types').UpdateRoundResponse> {
  const response = await fetch(`${API_BASE}/api/admin/rounds/${roundName}`, {
    method: 'PUT',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(request),
  });
  return response.json();
}

/**
 * 删除轮次
 */
export async function deleteRound(roundName: string): Promise<import('../types').DeleteRoundResponse> {
  const response = await fetch(`${API_BASE}/api/admin/rounds/${roundName}`, {
    method: 'DELETE',
  });
  return response.json();
}

// ==================== 轮次和抽签控制API ====================

/**
 * 设置当前轮次
 */
export async function setCurrentRound(roundName: string): Promise<{ success: boolean; tournament_state?: any; message?: string; error?: string }> {
  const response = await fetch(`${API_BASE}/api/admin/current-round`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ round: roundName }),
  });
  return response.json();
}

/**
 * 获取可以切换的下一轮列表
 */
export async function getAvailableNextRounds(): Promise<{ success: boolean; available_rounds?: any[]; message?: string; error?: string }> {
  const response = await fetch(`${API_BASE}/api/admin/available-next-rounds`, {
    method: 'GET',
    headers: {
      'Content-Type': 'application/json',
    },
  });

  return await response.json();
}

/**
 * 开启指定轮次的抽签
 */
export async function enableDrawForRound(roundName: string): Promise<{ success: boolean; tournament_state?: any; message?: string; error?: string }> {
  const response = await fetch(`${API_BASE}/api/admin/enable-draw`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ round: roundName }),
  });
  return response.json();
}

/**
 * 关闭抽签
 */
export async function disableDraw(): Promise<{ success: boolean; tournament_state?: any; message?: string; error?: string }> {
  const response = await fetch(`${API_BASE}/api/admin/disable-draw`, {
    method: 'POST',
  });
  return response.json();
}

/**
 * 检查并处理轮空晋级
 */
export async function checkByeAdvancement(roundName: string): Promise<{ success: boolean; tournament_state?: any; message?: string; error?: string }> {
  const response = await fetch(`${API_BASE}/api/tournament/check-bye-advancement`, {
    method: 'POST',
    headers: {
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({ round_name: roundName }),
  });
  return response.json();
}
